package com.xy.p2p.action.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.xy.common.page.Pagination;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.util.DictUtils;
import com.xy.common.web.CookieUtils;
import com.xy.common.web.RequestUtils;
import com.xy.core.web.WebErrors;
import com.xy.p2p.model.Trole;
import com.xy.p2p.model.Tuser;
import com.xy.p2p.service.TroleService;
import com.xy.p2p.service.TuserService;

@Controller
public class TuserAction {
	private static final Logger log = LoggerFactory
			.getLogger(TuserAction.class);
	public static final String COOKIE_ERROR_REMAINING = "_error_remaining";
	public static final String RETURN_URL = "returnUrl";
	public static final String MESSAGE = "message";
	public static final String AUTH_KEY = "auth_key";

	public TuserAction() {
	}
	
	@RequestMapping(value = "/logout.do")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Object auth =  request.getSession().getAttribute(AUTH_KEY);
		if (auth != null) {
			request.getSession().invalidate();
		}
		String returnUrl = RequestUtils.getQueryParam(request, RETURN_URL);
		String view = getView( returnUrl);
		if (view != null) {
			return view;
		} else {
			return "redirect:login.do";
		}
	}

	/**
	 * 登陆页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String login(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String returnUrl = RequestUtils.getQueryParam(request, RETURN_URL);
		String message = RequestUtils.getQueryParam(request, MESSAGE);
		Object auth =  request.getSession().getAttribute(AUTH_KEY);
		if (auth != null) {
			// 存在认证ID
			String view = getView(returnUrl);
			if (view != null) {
				return view;
			} else {
				return "login";
			}
		}
		writeCookieErrorRemaining(null, request, response, model);

		if (!StringUtils.isBlank(returnUrl)) {
			model.addAttribute(RETURN_URL, returnUrl);
		}
		if (!StringUtils.isBlank(message)) {
			model.addAttribute(MESSAGE, message);
		}
		return "login";
	}

	/**
	 * 用户登陆
	 * 
	 * @param username
	 * @param password
	 * @param captcha
	 * @param processUrl
	 * @param returnUrl
	 * @param message
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String loginSubmit(String username, String password, String captcha,
			String processUrl, String returnUrl, String message,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		WebErrors errors = validateLogin(username, password, captcha, null,
				request, response);
		if (!errors.hasErrors()) {
			try {
				String ip = RequestUtils.getIpAddr(request);
				tuserService.login(request, username, password);
				removeCookieErrorRemaining(request, response);
				String view = getView(returnUrl);
				// cmsLogMng.loginSuccess(request, user,
				// "login.log.loginSuccess");
				if (view != null) {
					return view;
				} else {
					return "redirect:index.do";
				}
			} catch (UsernameNotFoundException e) {
				errors.addErrorString(e.getMessage());
				// cmsLogMng.loginFailure(request, "login.log.loginFailure",
				// "username=" + username + ";password=" + password);
			} catch (BadCredentialsException e) {
				errors.addErrorString(e.getMessage());
				// cmsLogMng.loginFailure(request, "login.log.loginFailure",
				// "username=" + username + ";password=" + password);
			}
		}
		// 登录失败
		writeCookieErrorRemaining(null, request, response, model);
		errors.toModel(model);
		if (!StringUtils.isBlank(returnUrl)) {
			model.addAttribute(RETURN_URL, returnUrl);
		}
		if (!StringUtils.isBlank(message)) {
			model.addAttribute(MESSAGE, message);
		}
		return "login";
	}

 	/**
	 * 用户表新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tuserAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("tuser", new Tuser());
		setDict(model);
		model.addAttribute("roleList", troleService.getAll());
		return "tuserAdd";
	}

	/**
	 * 用户表新增保存
	 * 
	 * @param tuser
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/o_tuserSave.do")
	public String save(Tuser tuser, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(tuser, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		String roleIds[] = request.getParameterValues("roleIds");
		if (roleIds != null) {
			for (String id : roleIds) {
				Trole r = troleService.get(Long.parseLong(id));
				tuser.getTroles().add(r);
			}
		}

		if (tuser.getTroles() == null||tuser.getTroles() .size()==0) {
			tuser.setTroles(null);
		}
		if("".equals(tuser.getPasswd()))
			tuser.setPasswd(null);
		tuser = tuserService.save(tuser);
		return "redirect:v_tuserList.do";
	}

	/**
	 * 用户表删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_tuserDelete.do")
	public String delete(long[] ids) {
		if (ids != null) {
			for (long id : ids) {
				tuserService.remove(id);
			}
		}
		return "redirect:v_tuserList.do";
	}

	/**
	 * 用户表编辑页面
	 * 
	 * @param userid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tuserEdit.do")
	public String edit(long userid, HttpServletRequest request, ModelMap model) {
		Tuser tuser = tuserService.get(userid);
		model.addAttribute("tuser", tuser);
		List<Long> rids=new ArrayList<Long>();
		Set<Trole> set=tuser.getTroles();
		for(Trole r:set)
			rids.add(r.getRoleid());
			
		model.addAttribute("roleIds", rids);
		model.addAttribute("roleList", troleService.getAll());
		model.addAttribute("actionEdit", request.getParameter("request"));
		setDict(model);
		return "tuserEdit";
	}

	/**
	 * 用户表详情
	 * 
	 * @param userid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tuserDetail.do")
	public String detail(long userid, HttpServletRequest request, ModelMap model) {
		Tuser tuser = tuserService.get(userid);
		model.addAttribute("tuser", tuser);
        setDict(model);
		return "tuserView";
	}

	/**
	 * 用户表查询（分页）
	 * 
	 * @param tuser
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tuserList.do")
	public String listPage(Tuser tuser, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tuserService.getTuserByPage(toMap(tuser),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
		return "tuserList";
	}

	/**
	 * 用户表查询
	 * 
	 * @param tuser
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tuserList1.do")
	public String list(Tuser tuser, HttpServletRequest request, ModelMap model) {
		List<Tuser> list = tuserService.getTuser(toMap(tuser));
		model.addAttribute("list", list);
        setDict(model);
		return "tuserList";
	}
	@RequestMapping(value = "check_username.do")
	public void check_username(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			String username = request.getParameter("username");
			if (username == null || username.equals("")) {
				response.getWriter().write("false");
				return;
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("username", username);
			List l = tuserService.getTuser(param);
			String text = l.size() == 0 ? "true" : "false";
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(text);
		} catch (Exception e) {
			log.error(e.toString());
			throw e;
		}

	}

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tuser
	 * @return
	 */	private Map<String,Object> toMap(Tuser tuser){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(tuser.getUserid()!=null&&!tuser.getUserid().equals("")){
			map.put("userid", tuser.getUserid());
		}
		if(tuser.getUsername()!=null&&!tuser.getUsername().equals("")){
			map.put("username", tuser.getUsername());
		}
		if(tuser.getTruename()!=null&&!tuser.getTruename().equals("")){
			map.put("truename", tuser.getTruename());
		}
		if(tuser.getPasswd()!=null&&!tuser.getPasswd().equals("")){
			map.put("passwd", tuser.getPasswd());
		}
		if(tuser.getSex()!=null&&!tuser.getSex().equals("")){
			map.put("sex", tuser.getSex());
		}
		if(tuser.getPhone()!=null&&!tuser.getPhone().equals("")){
			map.put("phone", tuser.getPhone());
		}
		if(tuser.getEmail()!=null&&!tuser.getEmail().equals("")){
			map.put("email", tuser.getEmail());
		}
		if(tuser.getStatus()!=null&&!tuser.getStatus().equals("")){
			map.put("status", tuser.getStatus());
		}
		if(tuser.getRegip()!=null&&!tuser.getRegip().equals("")){
			map.put("regip", tuser.getRegip());
		}
		if(tuser.getLogtimes()!=null&&!tuser.getLogtimes().equals("")){
			map.put("logtimes", tuser.getLogtimes());
		}
		if(tuser.getErrtimes()!=null&&!tuser.getErrtimes().equals("")){
			map.put("errtimes", tuser.getErrtimes());
		}
		if(tuser.getLastloginip()!=null&&!tuser.getLastloginip().equals("")){
			map.put("lastloginip", tuser.getLastloginip());
		}
		if(tuser.getLastlogintime()!=null&&!tuser.getLastlogintime().equals("")){
			map.put("lastlogintime", tuser.getLastlogintime());
		}
		if(tuser.getRegtime()!=null&&!tuser.getRegtime().equals("")){
			map.put("regtime", tuser.getRegtime());
		}
		if(tuser.getModtime()!=null&&!tuser.getModtime().equals("")){
			map.put("modtime", tuser.getModtime());
		}      
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
      model.addAttribute("sexMap", DictUtils.getDictByType(DictUtils.TUSER_SEX));		
	}

	/**
	 * 获得返回页面
	 * 
	 * @param processUrl
	 * @param returnUrl
	 * @param authId
	 * @param defaultUrl
	 * @return
	 */
	private String getView(String returnUrl) {
		if (!StringUtils.isBlank(returnUrl)) {
			StringBuilder sb = new StringBuilder("redirect:");
			sb.append(returnUrl);
			return sb.toString();
		} else {
			return null;
		}
	}

	private void writeCookieErrorRemaining(Integer userErrorRemaining,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		// 所有访问的页面都需要写一个cookie，这样可以判断已经登录了几次。
		Integer errorRemaining = getCookieErrorRemaining(request, response);
		Integer errorInterval = 30;
		if (userErrorRemaining != null
				&& (errorRemaining == null || userErrorRemaining < errorRemaining)) {
			errorRemaining = userErrorRemaining;
		}
		int maxErrorTimes = 3;
		if (errorRemaining == null || errorRemaining > maxErrorTimes) {
			errorRemaining = maxErrorTimes;
		} else if (errorRemaining <= 0) {
			errorRemaining = 0;
		} else {
			errorRemaining--;
		}
		model.addAttribute("errorRemaining", errorRemaining);
		CookieUtils.addCookie(request, response, COOKIE_ERROR_REMAINING,
				errorRemaining.toString(), errorInterval * 60, null);
	}

	private WebErrors validateSave(Tuser tuser, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateLogin(String username, String password,
			String captcha, Integer errorRemaining, HttpServletRequest request,
			HttpServletResponse response) {
		WebErrors errors = WebErrors.create(request);
		if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}
		if (errors.ifOutOfLength(password, "password", 1, 32)) {
			return errors;
		}
		// 如果输入了验证码，那么必须验证；如果没有输入验证码，则根据当前用户判断是否需要验证码。
		if (!StringUtils.isBlank(captcha)
				|| (errorRemaining != null && errorRemaining < 0)) {
			if (errors.ifBlank(captcha, "captcha", 100)) {
				return errors;
			}
			try {
				if (!imageCaptchaService.validateResponseForID(request
						.getSession().getId(), captcha)) {
					errors.addError("error.invalidCaptcha");
					return errors;
				}
			} catch (CaptchaServiceException e) {
				errors.addError("error.exceptionCaptcha");
				log.warn("", e);
				return errors;
			}
		}
		return errors;
	}

	private void removeCookieErrorRemaining(HttpServletRequest request,
			HttpServletResponse response) {
		CookieUtils.cancleCookie(request, response, COOKIE_ERROR_REMAINING,
				null);
	}

	private Integer getCookieErrorRemaining(HttpServletRequest request,
			HttpServletResponse response) {
		Cookie cookie = CookieUtils.getCookie(request, COOKIE_ERROR_REMAINING);
		if (cookie != null) {
			String value = cookie.getValue();
			if (NumberUtils.isDigits(value)) {
				return Integer.parseInt(value);
			}
		}
		return null;
	}
	@Resource
	private TroleService troleService;
	@Autowired
	private ImageCaptchaService imageCaptchaService;
	@Resource
	private TuserService tuserService;
	private Long userid;
}